package com.cxs.musicplaywidget.service;

import com.cxs.musicplaywidget.data.MDevice;
import com.cxs.musicplaywidget.util.LogUtils;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.data.preferences.Preferences;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.utils.zson.ZSONObject;

import static ohos.distributedhardware.devicemanager.DeviceInfo.DeviceType.*;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

public class DeviceManager {
    private static final String tag = DeviceManager.class.getSimpleName();
    private volatile static DeviceManager instance = null;
    private static List<MDevice> deviceList = new CopyOnWriteArrayList<>();
    private final Context context;
    private static byte currentIndex;

    private DeviceManager(Context context) {
        this.context = context;
        init();
    }

    public static DeviceManager getInstance(Context context) {
        if (instance == null) {
            synchronized (DeviceManager.class) {
                if (instance == null) {
                    instance = new DeviceManager(context);
                }
            }
        }
        return instance;
    }

    public void init() {
        getDeviceList(true);
    }

    public void setCurrentIndex(byte currentIndex) {
        instance.currentIndex = currentIndex;
    }

    public byte getCurrentIndex() {
        return currentIndex;
    }

    public byte getCount() {
        return (byte)deviceList.size();
    }

    /**
     * 获取当前设备
     * @return
     */
    public MDevice getDevice() {
        return getDevice(currentIndex);
    }

    /**
     * 获取指定索引的设备
     * @param index
     * @return
     */
    public MDevice getDevice(byte index) {
        getDeviceList(false);
        if (!deviceList.isEmpty() && index < deviceList.size()) {
            return deviceList.get(index);
        }
        return null;
    }

    /**
     * 添加设备到列表开头
     * @param device
     */
    private void addFirst(MDevice device) {
        synchronized (deviceList) {
            if (!deviceList.contains(device)) {
                deviceList.add(0, device);
            }
        }
    }

    /**
     * 向列表添加设备
     * @param device
     */
    private void add(MDevice device) {
        synchronized (deviceList) {
            if (!deviceList.contains(device)) {
                deviceList.add(device);
            }
        }
    }


    public List<MDevice> getDeviceList() {
        return getDeviceList(false);
    }

    /**
     * 获取设备列表
     * @param reload
     * @return
     */
    public List<MDevice> getDeviceList(boolean reload) {
        synchronized (deviceList) {
            LogUtils.debug(tag, "getDeviceList.deviceList = " + deviceList);
            if (!reload) {
                // 如果不重新加载，则从内存中读取
                if (!deviceList.isEmpty()) {
                    return deviceList;
                }
            }

            deviceList.clear();
            // 添加本地设备到DeviceProvider
            addFirst(createDevice((byte)0, "", "本机", getLocalDeviceType().name().toLowerCase(), ""));
            LogUtils.debug(tag, "getDeviceList.deviceList = " + deviceList);

            // 远程设备列表
            List<DeviceInfo> list = ohos.distributedschedule.interwork.DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE);
            if (list != null && list.size() > 0) {
                // 遍历远程设备并添加到DeviceProvider
                for (byte i = 0; i < list.size(); i++) {
                    add(createDevice((byte)(i + 1),
                            list.get(i).getDeviceId(),
                            list.get(i).getDeviceName(),
                            list.get(i).getDeviceType().name().toLowerCase(),
                            ""));
                }
            }
            return deviceList;
        }
    }

    /**
     * 判断该设备是否已连接
     * @param index
     * @return
     */
    public synchronized boolean isConnected(byte index) {
        MDevice device = getDevice(index);
        if (device == null || device.proxy() == null) {
            return false;
        }
        return device.proxy().isConnected();
    }

    /**
     * 创建设备
     * @param i 索引
     * @param deviceId 设备Id
     * @param name 设备名称
     * @param type 设备类型
     * @param cls 在卡片中的样式
     * @return
     */
    private MDevice createDevice(byte i, String deviceId, String name, String type, String cls) {
        MDevice device = new MDevice();
        device.setIndex(i);
        device.setDeviceId(deviceId);
        device.setName(name);
        device.setType(type);
        device.setCls(cls);
        return device;
    }

    public String getLocalDeviceId() {
        KvManagerConfig kvManagerConfig = new KvManagerConfig(context);
        return KvManagerFactory.getInstance().createKvManager(kvManagerConfig).getLocalDeviceInfo().getId();
    }

    private String getLocalDeviceName() {
        KvManagerConfig kvManagerConfig = new KvManagerConfig(context);
        return KvManagerFactory.getInstance().createKvManager(kvManagerConfig).getLocalDeviceInfo().getName();
    }

    private DeviceInfo.DeviceType getLocalDeviceType() {
        KvManagerConfig kvManagerConfig = new KvManagerConfig(context);
        int type = Integer.parseInt(KvManagerFactory.getInstance().createKvManager(kvManagerConfig).getLocalDeviceInfo().getType());
        if (type == PHONE.value()) {
            return DeviceInfo.DeviceType.SMART_PHONE;
        } else if (type == TABLET.value()){
            return DeviceInfo.DeviceType.SMART_PAD;
        } else if (type == TV.value()) {
            return DeviceInfo.DeviceType.SMART_TV;
        } else if (type == CAR.value()) {
            return DeviceInfo.DeviceType.SMART_CAR;
        } else if (type == WEARABLE.value()) {
            return DeviceInfo.DeviceType.SMART_WATCH;
        }
        return DeviceInfo.DeviceType.UNKNOWN_TYPE;
    }
}

